﻿using System.Web.Mvc;
using System.Web.Routing;
using AutoMapper;
using AutoMapper.Mappers;
using Microsoft.ComponentModel.Composition.Extensions.Web;
using Steve.EFDataLayer;
using Steve.UI.Administration;
using Steve.UI.Administration.DataAnnotations;

namespace Steve.UI.Site
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : MefHttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "default", // Route name
                "{controller}/{action}/{id}/{*pathInfo}", // URL with parameters
                new
                {
                    controller = "Home",
                    action = "Index",
                    id = UrlParameter.Optional,
                    pathInfo = UrlParameter.Optional,
                    namespaces = "Steve.UI.Site.Controllers"
                } // Parameter defaults
            );
            routes.MapRoute(
                "home",
                "",
                new
                {
                    controller = "Home",
                    action = "Index",
                    namespaces = "Steve.UI.Site.Controllers"
                }
            );

        }

        protected override void Application_End()
        {
            base.Application_End();
        }

        protected override void Application_Start()
        {
            base.Application_Start();

            //HACK: bad hack to fix automapper temporarily...
            MapperRegistry.AllMappers = () =>
            {
                return new IObjectMapper[] { 
                     new FixedDataReaderMapper(), 
                     new TypeMapMapper(TypeMapObjectMapperRegistry.AllMappers.Invoke()), 
                     new StringMapper(), 
                     new FlagsEnumMapper(), 
                     new EnumMapper(), 
                     new ArrayMapper(), 
                     new EnumerableToDictionaryMapper(), 
                     new DictionaryMapper(), 
                     new ListSourceMapper(), 
                     new CollectionMapper(), 
                     new EnumerableMapper(), 
                     new AssignableMapper(), 
                     new TypeConverterMapper(), 
                     new NullableMapper() 
                 };
            };

            Mapper.Reset();

            ControllerBuilder.Current.SetControllerFactory(new MefControllerFactory(ScopeManager));
            ModelMetadataProviders.Current = new AdministrationModelMetadataProvider();

            SteveAdministrationSite.Initialize(ScopeManager);

            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

        }
    }
}